/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: PostParams.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.params;


import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import io.bhex.baselib.network.request.PostRequestBuilder;


public class PostParams extends AbstractParams implements IPostParams {
    private static final long serialVersionUID = -2230622301352829649L;
    private Map<String, Object> postParamsMap;

    private Map<String, File> fileMap;

    private URL urlObject = null;

    public PostParams(Builder<? extends Builder, ? extends PostParams> builder) {
        super(builder);
        this.postParamsMap = new HashMap<>();
        this.fileMap = new HashMap<>();

        if (builder.baseParams != null) {
            PostParams base = builder.baseParams;

            postParamsMap.putAll(base.postParamsMap);

            fileMap.putAll(base.fileMap);
        }

        this.postParamsMap.putAll(builder.postMap);
        this.fileMap.putAll(builder.fileMap);
    }

    @Override
    public Map<String, Object> postParams() {
        return postParamsMap;
    }

    @Override
    public Map<String, File> files() {
        return fileMap;
    }


    @Override
    public URL getUrlObject() {
        if (urlObject == null) {
            try {
                urlObject = new URL(url);
            } catch (MalformedURLException e) {
                // todo: 暂时吞掉url解析错误
                e.printStackTrace();
            }
        }

        return urlObject;
    }

    @Override
    public String getRequestBuilderClazz() {
        return PostRequestBuilder.class.getName();
    }

    public static class Builder<S extends Builder, T extends PostParams> extends AbstractParams.Builder<S, T> {

        Map<String, Object> postMap = new HashMap<>();

        Map<String, File> fileMap = new HashMap<>();

        /**
         * 用{@link #addParam(String, Object)} 代替
         *
         * @param key
         * @param value
         * @return
         */
        @Deprecated
        public S addPostParam(String key, Object value) {
            return addParam(key, value);
        }

        @Override
        public S addParam(String key, Object value) {
            postMap.put(key, value);
            return (S) this;
        }

        public S addFile(String key, File file) {
            if (file.exists() && file.isFile())
                fileMap.put(key, file);
            return (S) this;
        }

        public T build() {
            if (tag == null)
                tag = url;

            return (T) new PostParams(this);
        }
    }

}
